package cn.com.zhbs.logic.login.controller;

import cn.com.zhbs.common.jedis.JedisClient;
import cn.com.zhbs.login.entitys.Room;
import cn.com.zhbs.netty.EchoServerSender;
import cn.com.zhbs.netty.messageListener.LogicService;
import cn.com.zhbs.netty.protobuf.C2SLoginOuterClass;
import cn.com.zhbs.netty.protobuf.S2CAccountInfoOuterClass;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.AttributeKey;
import io.netty.util.concurrent.ImmediateEventExecutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录到netty服务器，客户端口通过token获取连接合法性，如果token合法，将当前socket加入到Group
 */
@Service("1")
public class Login extends EchoServerSender implements LogicService {
    @Resource
    JedisClient jedisClient;

    @Override
    public void task(byte[] data, ChannelHandlerContext ctx) {
      try {
          C2SLoginOuterClass.C2SLogin login= C2SLoginOuterClass.C2SLogin.parseFrom(data);
          System.out.println( "Server received: " + login.getToken());
          Boolean exists=jedisClient.exists(login.getToken());
          if(exists){
              String aid=jedisClient.get(login.getToken());
              ctx.channel().attr(AttributeKey.valueOf("aid")).set(aid);
              ChannelGroup channelGroup=Room.map.get(aid);
              if(channelGroup==null){
                  System.out.println(ctx.channel().remoteAddress()+"创建了房间："+aid);
                  channelGroup=new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE);
                  channelGroup.add(ctx.channel());
                  Room.map.put(aid,channelGroup);
              }else{
                  System.out.println(ctx.channel().remoteAddress()+"加入了房间："+aid);
                  channelGroup.add(ctx.channel());
              }
              System.out.println("当前房间人数："+channelGroup.size());
              Map<String, Object> map=new HashMap<>();
              map.put("aid",aid);
              Map<String,Object> accountMap=new HashMap<>();
              S2CAccountInfoOuterClass.S2CAccountInfo.Builder builder= S2CAccountInfoOuterClass.S2CAccountInfo.newBuilder();
              builder.setUsername(accountMap.get("username").toString());
              builder.setPhone(accountMap.get("mobilephone").toString());
              final S2CAccountInfoOuterClass.S2CAccountInfo accountInfo=builder.build();
              this.channelSend(ctx,2,accountInfo.toByteArray());
          }else{
             ctx.close();
          }
      }catch (Exception e){
          e.printStackTrace();
      }
    }

    @Override
    public void channelSend(ChannelHandlerContext ctx, int msg, byte[] body) {
        super.channelSend(ctx, msg, body);
    }
}
